package lightcar;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import java.lang.Thread;

public class LightCar
{
    public static final boolean input_debug = false;
    public static final boolean animation_debug = false;
    private static final int ms_between_steps = 100;
    
    static World world;
    static MyFrame mainFrame;
    static private boolean paused;
    private static Timer timer;
    private static long num_steps;
    
    
    
    static class Animation extends TimerTask
    {
        Date next_step;
        Date current_time;
        
        Animation()
        {
            next_step = new Date();
        }
        
        @Override
        public void run()
        {
            while(!paused)
            {
                //Wait until it is time to execute the step
                current_time = new Date();
                while(current_time.before(next_step))
                {
                    try{
                        if(animation_debug) System.out.println("Sleep time: " + (next_step.getTime()-current_time.getTime()));
                        Thread.sleep(next_step.getTime()-current_time.getTime());
                    }
                    catch (InterruptedException e) {}
                    catch (IllegalArgumentException e){}
                    current_time = new Date();
                }
                if(paused)
                {
                    break;
                }
                
                //Set the time for the next step
                next_step.setTime(next_step.getTime() + ms_between_steps);
                current_time = new Date();
                if(next_step.getTime() < current_time.getTime())
                {
                    System.out.println("The system can't keep up. Try increasing LightCar.ms_between_steps");
                }
                
                //Execute step and repaint
                if(animation_debug) System.out.println("Starting Step " + num_steps);
                world.moveAll();
                mainFrame.repaint();
                num_steps++;
            }
        }
    }
    
    public static void main(String[] args) 
    {
        System.out.println("Robotics Program Started.");
     
        paused = true;
        timer = new Timer();
        world = new World();
        mainFrame = new MyFrame();
        num_steps = 0;
        
        //mainFrame = new MyFrame();
        mainFrame.setSize(970, 700);
        mainFrame.setVisible(true);
    }
    
    public static void start()
    {
        if(paused)
        {
            paused = false;
            timer.schedule(new Animation(), 1);
        }
    }
    
    public static void pause()
    {
        paused = true;
    }
    
}
